<template>
    <div class="user_info">
        name:
        <input type="text" v-model="userDetail.name" />
        <br />
        desc:
        <input type="text" v-model="userDetail.desc" />
        <br />
        头像：
        <br />
        <div class="edit_upload_image">
            <div class="image">
                <img :src="userDetail.image" alt="" />
            </div>
            <div class="action">
                <el-upload
                    class="upload-demo"
                    multiple
                    :limit="3"
                    action="/api/tools/saveavatar"
                    :before-upload="beforeUpload"
                >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                        只能上传jpg/png文件，且不超过500kb
                    </div>
                </el-upload>
            </div>
        </div>
        <button @click="edit">编辑</button>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        return {
            userDetail: {
                user: '',
                name: '',
                desc: '',
                image: '',
            },
        }
    },
    computed: {
        userData() {
            return this.$store.state.userData
        },
    },
    created() {
        // 防止拷贝一个引用地址
        console.log(this.userData)
        this.userDetail.user = this.userData.user
        this.userDetail.name = this.userData.name
        this.userDetail.desc = this.userData.desc
        this.userDetail.image = this.userData.image
    },
    methods: {
        beforeUpload(file) {
            let fd = new FormData() //通过form数据格式来传
            fd.append('file', file) //传文件
            axios
                .post('/api/tools/saveavatar', fd)
                .then((res) => {
                    let data = res
                    if (data.code == 200) {
                        this.userDetail.image = data.data.file
                        this.$message({
                            message: '上传成功',
                            type: 'success',
                        })
                    } else {
                        this.$message.error('message')
                    }
                })
                .catch((error) => {
                    // console.log(error);
                })
        },
        edit() {
            this.$api.editUser(this.userDetail).then((res) => {
                if (res.code === 1) {
                    this.$message({
                        type: 'success',
                        message: '成功',
                    })
                    this.$store.commit('setUserData', res.data)
                }
            })
        },
    },
}
</script>

<style>
</style>